package models.crawlers;

import models.crawlers.common.*;
import models.entities.ProductEntity;
import models.helpers.StringHelper;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Slami extends ShopCrawler {

    private Map<String, String> allProductsCookie;


    public Slami() {
        crawlerMainUrl = "http://slami.ru";
        allProductsCookie = new HashMap<String, String>();
        allProductsCookie.put("itemsPerPage", "all");

    }

    @Override
    protected WebSiteInfo initializeWebSiteInfo() {
        SitePathInfo categoryPath = new SitePathInfo();
        categoryPath.url = crawlerMainUrl + "/netcat/modules/catalog/";
        categoryPath.title = "SLAMI";
        return new WebSiteInfo(categoryPath, 671, 16798);
    }

    @Override
    public List<CategoryInfo> getCategories(String url) throws IOException {
        List<CategoryInfo> categories = new ArrayList<CategoryInfo>();
        Document categoryPage = downloadPage(url, allProductsCookie);
        Elements childElements = categoryPage.select(".sections .catalog");
        for (Element element : childElements) {
            String childCategoryTitle = element.text().trim();
            String childCategoryUrl = getSourceUrl(element.attr("href"));
            CategoryInfo categoryInfo = new CategoryInfo(childCategoryTitle, childCategoryUrl);
            categories.add(categoryInfo);
        }
        return categories;
    }

    @Override
    public List<ProductInfo> getProducts(String url, int pageNumber) throws IOException {
        Document categoryPage = downloadPage(url, allProductsCookie);
        Elements products = categoryPage.select(".goods_plitka td");
        List<ProductInfo> productInfos = new ArrayList<ProductInfo>();
        for (Element productElement : products) {
            ProductInfo productInfo = new ProductInfo();
            Elements productAnchorElement = productElement.select(".name a");
            productInfo.title = productAnchorElement.text().trim();
            productInfo.url = getSourceUrl(productAnchorElement.attr("href"));
            productInfos.add(productInfo);
        }
        return productInfos;
    }


    protected int getCategoryProductsCount(String categoryUrl) throws IOException {
        Document categoryPage = downloadPage(categoryUrl, allProductsCookie);
        Elements products = categoryPage.select(".goods_plitka td .name a");
        return products.size();
    }

    protected String getProductSourceId(String productUrl) {
        String persistentUrlPart = crawlerMainUrl + "/netcat/modules/catalog/";
        return productUrl.replace(persistentUrlPart, "");
    }

    @Override
    protected Integer findNextPage(Integer pageNumber, String url) throws IOException {
        return null;
    }

    @Override
    public ProductEntity getProduct(String url) throws Exception {
        try {
            Document productPage = downloadPage(url);
            ProductEntity productEntity = new ProductEntity();
            Elements description = productPage.select(".good_details .description");
            Elements nameElements = productPage.select(".good_details h1");

            if (nameElements.size() > 0)
                productEntity.title = nameElements.text().trim();
            if (description.html().length() > 0) {
                productEntity.shortDescription = description.html().substring(description.html().indexOf("</h2>") + 5, description.html().indexOf("<br />")).trim();
            }
            Elements priceElement = productPage.select(".good_details .headblock .price .value");
            String priceText = priceElement.text().trim().replace(" ", "");
            if (StringHelper.isNumeric(priceText))
                productEntity.price = Double.parseDouble(priceText);

            if (description.html().length() > 0) {
                if (description.html().length() > (description.html().indexOf("<br />") + 14))
                    productEntity.description = description.html().substring(description.html().indexOf("<br />") + 14).trim();
            }
            Element brandTitleElement = productPage.select(".breadcrumb-navigation a").get(1);
            String brandTitle = brandTitleElement.text().trim().replace("_", " ");
            productEntity.brandName = brandTitle;
            addPictures(productEntity, productPage);
            return productEntity;
        } catch (Exception ex) {
            throw new ProductParsingException(ex);
        }
    }


    private void addPictures(ProductEntity productEntity, Document productPage) throws Exception {
        Elements picture = productPage.select(".good_details .headblock .photo a");
        if (picture.size() > 0) {
            String pictureUrl = String.format("%1$s%2$s", crawlerMainUrl, picture.attr("href"));
            productEntity.pictureUrls.add(pictureUrl);
        }
    }

}
